﻿using System;
using System.Diagnostics;
using System.Threading;

namespace UnionnetClient.Model
{
	public class LoginedState : StateBase
	{
		public LoginedState(StateMachine stateMachine) : base(stateMachine)
		{	
		}

		public event EventHandler<ConnectChangedEventArgs> ConnectedStateChanged;

		public int TestInterval
		{
			get { return this.testInterval; }
			set 
			{
				this.testInterval = value;
				if (timer != null)
				{
					timer.Change(testInterval, testInterval);
				}
			}
		}

		public void StartTestNetwork()
		{
			Debug.WriteLine("TestNetwork Start.");
			connected = true;
			timer = new Timer(TestNetwork, null, testInterval, testInterval); 
		}

		public void StopTestNetwork()
		{
			timer.Dispose();
		}

		#region 私有

		private Timer timer;
		private Timer disconnectedTimer;
		private int testInterval = 5000;
		private bool connected = true;


		protected virtual void OnConnectedStateChanged(bool r)
		{
			if (ConnectedStateChanged != null)
			{
				ConnectedStateChanged(this, new ConnectChangedEventArgs(r));
			}
		}

		private void TestNetwork(object o)
		{
			bool r = Roovent.Network.NetworkTool.GetIsConnectedToInternet();
			if (connected != r) //状态改变
			{
				OnConnectedStateChanged(r);
				connected = r;

				//长时间无法连接网络则返回未登陆模式
				if (!r)
				{
					disconnectedTimer = new Timer(SetToUnloginState, null, 10000, 0);
				}
				else
				{
					if (disconnectedTimer != null)
					{
						disconnectedTimer.Dispose();
					}
				}
			}
		}

		private void SetToUnloginState(object o)
		{
			this.StopTestNetwork();
			stateMachine.SetState(stateMachine.UnloginS);
		}
		#endregion
	}
}
